package com.kk.miaosha.securityEntity;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author : K k
 * @date : 10:17 2020/10/22
 */
@Component(value = "rbacService")
public class RbacService {

    /**
     * 根据用户的权限路径，动态判断权限
     * @return
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        /*System.out.println(authentication.getPrincipal());
        System.out.println(authentication.getDetails());
        System.out.println(authentication.getAuthorities());*/
        Object principal = authentication.getPrincipal();
        System.out.println(principal);
        boolean hasPermit=false;
        if (principal instanceof UserDetails){
            //若为UserDetails的实例对象
            principal=(UserDetail)principal;
            List<String> sourceList = ((UserDetail) principal).getSourceList();
            System.out.println(sourceList);
            AntPathMatcher antPathMatcher=new AntPathMatcher();
            for(String uri: sourceList){
                if (antPathMatcher.match(uri,request.getRequestURI())){
                    hasPermit=true;
                    break;
                }
            }
            return hasPermit;
        }
        return hasPermit;
    }
}
